<template>
	<view class="detail-container">
		<view class="header">
			<text class="title">菜品详情</text>
			<button class="back-btn" @click="handleBack">返回</button>
		</view>

		<view class="content">
			<view class="detail-card">
				<view class="detail-header">
					<text class="detail-title">基本信息</text>
					<view class="status-badge" :class="getStatusClass(dishData.status)">
						{{ dishData.status === 1 ? '启用' : '禁用' }}
					</view>
				</view>

				<view class="detail-body">
					<view class="detail-section">
						<view class="detail-item">
							<text class="label">菜品名称</text>
							<text class="value">{{ dishData.name || '-' }}</text>
						</view>

						<view class="detail-item">
							<text class="label">菜品分类</text>
							<text class="value">{{ dishData.categoryName || '-' }}</text>
						</view>


						<view class="detail-item">
							<text class="label">创建时间</text>
							<text class="value">{{ formatTime(dishData.create_date) }}</text>
						</view>

						<view class="detail-item">
							<text class="label">更新时间</text>
							<text class="value">{{ formatTime(dishData.update_date) }}</text>
						</view>
					</view>

					<view class="detail-section">
						<text class="section-title">菜品描述</text>
						<text class="description">{{ dishData.description || '暂无描述' }}</text>
					</view>

					<view class="detail-section">
						<text class="section-title">菜品材料</text>
						<view v-if="dishData.ingredients && (dishData.ingredients.main_ingredients || dishData.ingredients.auxiliary_ingredients || dishData.ingredients.seasonings)">
							<view class="detail-item" v-if="dishData.ingredients.main_ingredients">
								<text class="label">主材</text>
								<text class="value">{{ dishData.ingredients.main_ingredients }}</text>
							</view>
							<view class="detail-item" v-if="dishData.ingredients.auxiliary_ingredients">
								<text class="label">辅材</text>
								<text class="value">{{ dishData.ingredients.auxiliary_ingredients }}</text>
							</view>
							<view class="detail-item" v-if="dishData.ingredients.seasonings">
								<text class="label">调味品</text>
								<text class="value">{{ dishData.ingredients.seasonings }}</text>
							</view>
						</view>
						<text v-else class="description">暂无材料</text>
					</view>

					<view class="detail-section" v-if="dishData.image">
						<text class="section-title">菜品图片</text>
						<view class="image-preview">
							<image 
								:src="dishData.image" 
								mode="aspectFit" 
								class="preview-image"
								@click="previewImage"
							></image>
							<button class="preview-btn" @click="previewImage">查看大图</button>
						</view>
					</view>
				</view>

				<view class="detail-actions">
					<button class="btn btn-edit" @click="handleEdit">编辑</button>
					<button class="btn btn-delete" @click="handleDelete">删除</button>
					<button 
						class="btn btn-status" 
						:class="dishData.status === 1 ? 'btn-disable' : 'btn-enable'"
						@click="toggleStatus"
					>
						{{ dishData.status === 1 ? '禁用' : '启用' }}
					</button>
				</view>
			</view>
		</view>

		<!-- 删除确认弹窗 -->
		<uni-popup ref="deletePopup" type="dialog">
			<uni-popup-dialog 
				type="warn" 
				title="确认删除" 
				content="确定要删除这个菜品吗？此操作不可恢复。"
				:before-close="true"
				@confirm="confirmDelete"
				@close="cancelDelete"
			></uni-popup-dialog>
		</uni-popup>

		<!-- 状态切换确认弹窗 -->
		<uni-popup ref="statusPopup" type="dialog">
			<uni-popup-dialog 
				type="info" 
				:title="dishData.status === 1 ? '确认禁用' : '确认启用'" 
				:content="dishData.status === 1 ? '确定要禁用这个菜品吗？禁用后用户将无法看到该菜品。' : '确定要启用这个菜品吗？启用后用户将可以看到该菜品。'"
				:before-close="true"
				@confirm="confirmToggleStatus"
				@close="cancelToggleStatus"
			></uni-popup-dialog>
		</uni-popup>

		<!-- 图片预览弹窗 -->
		<uni-popup ref="imagePopup" type="center">
			<view class="image-modal">
				<image :src="dishData.image" mode="aspectFit" class="modal-image"></image>
				<button class="close-btn" @click="closeImagePreview">关闭</button>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const dishId = ref('')
const dishData = reactive({})
const deletePopup = ref(null)
const statusPopup = ref(null)
const imagePopup = ref(null)

onLoad((options) => {
	if (options.id) {
		dishId.value = options.id
		loadDishDetail()
	}
})

// 加载菜品详情
async function loadDishDetail() {
	uni.showLoading({ title: '加载中...' })
	try {
		const result = await uniCloud.callFunction({
			name: 'food-dishes',
			data: { action: 'get-dish-detail', data: { dishId: dishId.value } }
		})
		if (result.result.code === 200) {
			Object.assign(dishData, result.result.data)
			if (dishData.category_id) await loadCategoryName()
		} else {
			uni.showToast({ title: result.result.message || '获取菜品详情失败', icon: 'none' })
		}
	} catch (error) {
		console.error('获取菜品详情失败:', error)
		uni.showToast({ title: '获取详情失败', icon: 'none' })
	} finally {
		uni.hideLoading()
	}
}

// 加载分类名称
async function loadCategoryName() {
	try {
		const result = await uniCloud.callFunction({
			name: 'food-categories',
			data: { action: 'get-category-detail', data: { categoryId: dishData.category_id } }
		})
		if (result.result.code === 200) {
			dishData.categoryName = result.result.data.name
		}
	} catch (error) {
		console.error('加载分类名称失败:', error)
	}
}

// 格式化时间
function formatTime(timestamp) {
	if (!timestamp) return '-'
	let dateObj
	if (typeof timestamp === 'number') {
		dateObj = new Date(timestamp)
	} else if (typeof timestamp === 'string') {
		dateObj = new Date(timestamp)
	} else if (typeof timestamp === 'object' && timestamp.$date) {
		dateObj = new Date(timestamp.$date)
	} else {
		return '-'
	}
	const year = dateObj.getFullYear()
	const month = String(dateObj.getMonth() + 1).padStart(2, '0')
	const day = String(dateObj.getDate()).padStart(2, '0')
	const hours = String(dateObj.getHours()).padStart(2, '0')
	const minutes = String(dateObj.getMinutes()).padStart(2, '0')
	return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取状态样式类
function getStatusClass(status) {
	return status === 1 ? 'status-enabled' : 'status-disabled'
}

// 返回
function handleBack() { uni.navigateBack() }

// 编辑
function handleEdit() {
	uni.navigateTo({ url: `/pages/dishes/edit?id=${dishId.value}` })
}

// 删除
function handleDelete() { deletePopup.value?.open() }

// 确认删除
async function confirmDelete() {
	uni.showLoading({ title: '删除中...' })
	try {
		const result = await uniCloud.callFunction({
			name: 'food-dishes',
			data: { action: 'delete-dish', data: { dishId: dishId.value } }
		})
		if (result.result.code === 200) {
			uni.showToast({ title: '删除成功', icon: 'success' })
			setTimeout(() => { uni.navigateBack() }, 1500)
		} else {
			uni.showToast({ title: result.result.message || '删除失败', icon: 'none' })
		}
	} catch (error) {
		console.error('删除菜品失败:', error)
		uni.showToast({ title: '删除失败', icon: 'none' })
	} finally {
		uni.hideLoading()
	}
	deletePopup.value?.close()
}

// 取消删除
function cancelDelete() { deletePopup.value?.close() }

// 切换状态
function toggleStatus() { statusPopup.value?.open() }

// 确认切换状态
async function confirmToggleStatus() {
	const newStatus = dishData.status === 1 ? 0 : 1
	uni.showLoading({ title: '更新中...' })
	try {
		const result = await uniCloud.callFunction({
			name: 'food-dishes',
			data: { action: 'update-dish', data: { dishId: dishId.value, updateData: { status: newStatus } } }
		})
		if (result.result.code === 200) {
			dishData.status = newStatus
			uni.showToast({ title: '状态更新成功', icon: 'success' })
		} else {
			uni.showToast({ title: result.result.message || '状态更新失败', icon: 'none' })
		}
	} catch (error) {
		console.error('更新状态失败:', error)
		uni.showToast({ title: '状态更新失败', icon: 'none' })
	} finally {
		uni.hideLoading()
	}
	statusPopup.value?.close()
}

// 取消切换状态
function cancelToggleStatus() { statusPopup.value?.close() }

// 图片预览
function previewImage() { if (dishData.image) imagePopup.value?.open() }
function closeImagePreview() { imagePopup.value?.close() }
</script>

<style lang="scss" scoped>
	.detail-container {
		min-height: 100vh;
		background-color: #f5f5f5;

		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			background: white;
			border-bottom: 1rpx solid #eee;

			.title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}

			.back-btn {
				padding: 16rpx 32rpx;
				background: #f0f0f0;
				border: none;
				border-radius: 8rpx;
				font-size: 28rpx;
				color: #666;
				cursor: pointer;
			}
		}

		.content {
			padding: 20rpx;

			.detail-card {
				background: white;
				border-radius: 12rpx;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

				.detail-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx;
					border-bottom: 1rpx solid #eee;

					.detail-title {
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
					}

					.status-badge {
						padding: 8rpx 16rpx;
						border-radius: 20rpx;
						font-size: 24rpx;
						font-weight: bold;

						&.status-enabled {
							background: #f6ffed;
							color: #52c41a;
							border: 1rpx solid #b7eb8f;
						}

						&.status-disabled {
							background: #fff2f0;
							color: #ff4d4f;
							border: 1rpx solid #ffccc7;
						}
					}
				}

				.detail-body {
					padding: 30rpx;

					.detail-section {
						margin-bottom: 40rpx;

						&:last-child {
							margin-bottom: 0;
						}

						.section-title {
							display: block;
							font-size: 28rpx;
							font-weight: bold;
							color: #333;
							margin-bottom: 20rpx;
						}

						.detail-item {
							display: flex;
							justify-content: space-between;
							align-items: center;
							padding: 15rpx 0;
							border-bottom: 1rpx solid #f5f5f5;

							&:last-child {
								border-bottom: none;
							}

							.label {
								font-size: 28rpx;
								color: #666;
								min-width: 150rpx;
							}

							.value {
								font-size: 28rpx;
								color: #333;
								text-align: right;
								flex: 1;
							}
						}

						.description {
							display: block;
							font-size: 28rpx;
							color: #666;
							line-height: 1.6;
							padding: 20rpx;
							background: #fafafa;
							border-radius: 8rpx;
							min-height: 80rpx;
						}

						.image-preview {
							display: flex;
							flex-direction: column;
							align-items: center;
							gap: 20rpx;

							.preview-image {
								width: 300rpx;
								height: 200rpx;
								border-radius: 8rpx;
								border: 1rpx solid #eee;
								cursor: pointer;
							}

							.preview-btn {
								padding: 16rpx 32rpx;
								background: #007aff;
								color: white;
								border: none;
								border-radius: 8rpx;
								font-size: 26rpx;
								cursor: pointer;
							}
						}
					}
				}

				.detail-actions {
					display: flex;
					gap: 20rpx;
					padding: 30rpx;
					border-top: 1rpx solid #eee;

					.btn {
						flex: 1;
						padding: 24rpx;
						border: none;
						border-radius: 8rpx;
						font-size: 28rpx;
						cursor: pointer;

						&.btn-edit {
							background: #1890ff;
							color: white;
						}

						&.btn-delete {
							background: #ff4d4f;
							color: white;
						}

						&.btn-status {
							&.btn-enable {
								background: #52c41a;
								color: white;
							}

							&.btn-disable {
								background: #faad14;
								color: white;
							}
						}
					}
				}
			}
		}

		.image-modal {
			background: white;
			border-radius: 12rpx;
			padding: 30rpx;
			text-align: center;

			.modal-image {
				width: 500rpx;
				height: 400rpx;
				border-radius: 8rpx;
				margin-bottom: 20rpx;
			}

			.close-btn {
				padding: 16rpx 32rpx;
				background: #007aff;
				color: white;
				border: none;
				border-radius: 8rpx;
				font-size: 28rpx;
				cursor: pointer;
			}
		}

		@media (max-width: 750rpx) {
			.detail-container {
				padding: 15rpx;

				.header {
					padding: 15rpx;

					.title {
						font-size: 32rpx;
					}

					.back-btn {
						padding: 12rpx 24rpx;
						font-size: 26rpx;
					}
				}

				.content {
					padding: 15rpx;

					.detail-card {
						.detail-header {
							padding: 20rpx;
							flex-direction: column;
							gap: 15rpx;
							align-items: flex-start;

							.detail-title {
								font-size: 30rpx;
							}
						}

						.detail-body {
							padding: 20rpx;

							.detail-section {
								margin-bottom: 30rpx;

								.detail-item {
									flex-direction: column;
									align-items: flex-start;
									gap: 10rpx;

									.label {
										min-width: auto;
										font-weight: bold;
									}

									.value {
										text-align: left;
									}
								}
							}
						}

						.detail-actions {
							padding: 20rpx;
							flex-direction: column;
							gap: 15rpx;
						}
					}
				}

				.image-modal {
					padding: 20rpx;

					.modal-image {
						width: 350rpx;
						height: 250rpx;
					}
				}
			}
		}
	}
</style>